<template>
  <el-dialog
    v-model="dialogVisible"
    title="敏感词检测"
    width="800px"
    :before-close="handleClose"
  >
    <div class="sensitive-checker">
      <!-- 输入区域 -->
      <div class="input-section">
        <el-form :model="form" label-width="100px">
          <el-form-item label="检测内容">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="6"
              placeholder="请输入要检测的评论内容..."
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="checking"
              :disabled="!form.content.trim()"
              @click="handleCheck"
            >
              <el-icon><Search /></el-icon>
              开始检测
            </el-button>
            <el-button @click="handleClear">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 检测结果 -->
      <div v-if="checkResult" class="result-section">
        <el-divider content-position="left">检测结果</el-divider>

        <!-- 总体评估 -->
        <div class="overall-assessment">
          <el-card>
            <div class="assessment-header">
              <h4>总体评估</h4>
              <el-tag
                :type="checkResult.hasSensitiveWords ? 'danger' : 'success'"
                size="large"
              >
                {{ checkResult.hasSensitiveWords ? "包含敏感词" : "内容安全" }}
              </el-tag>
            </div>
            <div class="assessment-details">
              <div class="detail-item">
                <span class="label">敏感度评分:</span>
                <span class="value">
                  <el-progress
                    :percentage="checkResult.sensitiveScore"
                    :color="getScoreColor(checkResult.sensitiveScore)"
                    :show-text="false"
                    style="width: 200px; margin-right: 10px"
                  />
                  {{ checkResult.sensitiveScore }}分
                </span>
              </div>

              <div class="detail-item">
                <span class="label">主要类型:</span>
                <span class="value">
                  <el-tag type="warning">
                    {{ checkResult.primaryTypeText || "敏感内容" }}
                  </el-tag>
                </span>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 敏感词列表 -->
        <div
          v-if="checkResult.sensitiveWords.length > 0"
          class="sensitive-words"
        >
          <h4>检测到的敏感词 ({{ checkResult.sensitiveWords.length }}个)</h4>
          <div class="words-grid">
            <el-card
              v-for="(word, index) in checkResult.sensitiveWords"
              :key="index"
              class="word-card"
              shadow="hover"
            >
              <div class="word-header">
                <span class="word-text">{{ word.word }}</span>
                <el-tag :type="getSeverityTagType(word.severity)" size="small">
                  严重度: {{ word.severity }}
                </el-tag>
              </div>
              <div class="word-details">
                <div class="detail-row">
                  <span class="label">类型:</span>
                  <span class="value">{{
                    CommentManagementUtils.getSensitiveTypeText(word.type)
                  }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">位置:</span>
                  <span class="value">第 {{ word.position }} 个字符</span>
                </div>
                <div class="detail-row">
                  <span class="label">建议替换:</span>
                  <span class="value replacement">{{ word.replacement }}</span>
                </div>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 内容对比 */
        <div class="content-comparison">
          <h4>内容对比</h4>
          <el-row :gutter="16">
            <el-col :span="12">
              <div class="comparison-panel">
                <div class="panel-header">
                  <h5>原始内容</h5>
                </div>
                <div class="panel-content original">
                  {{ checkResult.originalContent }}
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="comparison-panel">
                <div class="panel-header">
                  <h5>过滤后内容</h5>
                  <el-button
                    size="small"
                    type="primary"
                    @click="copyFilteredContent"
                  >
                    复制
                  </el-button>
                </div>
                <div class="panel-content filtered">
                  {{ checkResult.filteredContent }}
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 操作建议 -->
        <div class="action-suggestions">
          <h4>操作建议</h4>
          <el-alert
            :title="getActionSuggestionTitle(checkResult.suggestedAction)"
            :type="getActionSuggestionType(checkResult.suggestedAction)"
            :description="
              getActionSuggestionDescription(checkResult.suggestedAction)
            "
            show-icon
            :closable="false"
          />
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button v-if="checkResult" type="primary" @click="handleExport">
          导出结果
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { Search, Delete } from "@element-plus/icons-vue";
import {
  checkSensitiveWordsApi,
  type SensitiveCheckResponse,
  CommentManagementUtils
} from "@/api/comment-management";

// Props
interface Props {
  visible: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
});

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  "check-result": [result: SensitiveCheckResponse];
}>();

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

const checking = ref(false);
const checkResult = ref<SensitiveCheckResponse | null>(null);

const form = ref({
  content: ""
});

// 方法
const handleCheck = async () => {
  if (!form.value.content.trim()) {
    ElMessage.warning("请输入要检测的内容");
    return;
  }

  checking.value = true;
  try {
    const data = await checkSensitiveWordsApi(form.value.content);

    if (data && data.code === 200) {
      checkResult.value = data.data;
      emit("check-result", data.data);
      ElMessage.success("检测完成");
    } else {
      ElMessage.error(data?.message || "检测失败");
    }
  } catch (error) {
    console.error("敏感词检测失败:", error);
    ElMessage.error("检测失败");
  } finally {
    checking.value = false;
  }
};

const handleClear = () => {
  form.value.content = "";
  checkResult.value = null;
};

const handleClose = () => {
  dialogVisible.value = false;
};

const handleExport = () => {
  if (!checkResult.value) return;

  const exportData = {
    检测时间: new Date().toLocaleString(),
    原始内容: checkResult.value.originalContent,
    过滤后内容: checkResult.value.filteredContent,
    敏感度评分: checkResult.value.sensitiveScore,
    是否包含敏感词: checkResult.value.hasSensitiveWords ? "是" : "否",
    敏感词列表: checkResult.value.sensitiveWords.map(word => ({
      敏感词: word.word,
      类型: word.type,
      严重度: word.severity,
      位置: word.position
    }))
  };

  const blob = new Blob([JSON.stringify(exportData, null, 2)], {
    type: "application/json"
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `敏感词检测结果_${Date.now()}.json`;
  a.click();
  URL.revokeObjectURL(url);

  ElMessage.success("导出成功");
};

const copyFilteredContent = async () => {
  if (!checkResult.value) return;

  try {
    await navigator.clipboard.writeText(checkResult.value.filteredContent);
    ElMessage.success("复制成功");
  } catch (error) {
    ElMessage.error("复制失败");
  }
};

// 工具方法

const getAssessmentText = (action: string) => {
  const textMap = {
    PASS: "通过",
    REVIEW: "需要审核",
    REJECT: "建议拒绝"
  };
  return textMap[action] || "未知";
};

const getAssessmentTagType = (action: string) => {
  const typeMap = {
    PASS: "success",
    REVIEW: "warning",
    REJECT: "danger"
  };
  return typeMap[action] || "info";
};

const getScoreColor = (score: number) => {
  if (score < 30) return "#67c23a";
  if (score < 70) return "#e6a23c";
  return "#f56c6c";
};

const getSeverityTagType = (severity: number) => {
  if (severity <= 2) return "success";
  if (severity <= 3) return "warning";
  return "danger";
};

const getActionSuggestionTitle = (action: string) => {
  const titleMap = {
    PASS: "内容安全",
    REVIEW: "需要人工审核",
    REJECT: "建议拒绝"
  };
  return titleMap[action] || "未知状态";
};

const getActionSuggestionType = (action: string) => {
  const typeMap = {
    PASS: "success",
    REVIEW: "warning",
    REJECT: "error"
  };
  return typeMap[action] || "info";
};

const getActionSuggestionDescription = (action: string) => {
  const descMap = {
    PASS: "该内容未检测到敏感词，可以正常发布。",
    REVIEW: "该内容包含可能的敏感词，建议人工审核后决定是否发布。",
    REJECT: "该内容包含明显的敏感词，建议拒绝发布。"
  };
  return descMap[action] || "无建议";
};

// 监听对话框关闭，清理数据
watch(dialogVisible, newVal => {
  if (!newVal) {
    setTimeout(() => {
      handleClear();
    }, 300);
  }
});
</script>

<style scoped lang="scss">
.sensitive-checker {
  .input-section {
    margin-bottom: 20px;
  }

  .result-section {
    .overall-assessment {
      margin-bottom: 20px;

      .assessment-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;

        h4 {
          margin: 0;
          color: #303133;
        }
      }

      .assessment-details {
        .detail-item {
          display: flex;
          align-items: center;
          margin-bottom: 12px;

          .label {
            min-width: 80px;
            margin-right: 12px;
            font-weight: 500;
            color: #606266;
          }

          .value {
            display: flex;
            align-items: center;
            color: #303133;
          }
        }
      }
    }

    .sensitive-words {
      margin-bottom: 20px;

      h4 {
        margin-bottom: 16px;
        color: #303133;
      }

      .words-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 16px;

        .word-card {
          .word-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;

            .word-text {
              font-size: 16px;
              font-weight: 600;
              color: #f56c6c;
            }
          }

          .word-details {
            .detail-row {
              display: flex;
              margin-bottom: 8px;
              font-size: 14px;

              .label {
                min-width: 60px;
                margin-right: 8px;
                color: #909399;
              }

              .value {
                color: #303133;

                &.replacement {
                  padding: 2px 6px;
                  font-family: monospace;
                  background: #f5f7fa;
                  border-radius: 4px;
                }
              }
            }
          }
        }
      }
    }

    .content-comparison {
      margin-bottom: 20px;

      h4 {
        margin-bottom: 16px;
        color: #303133;
      }

      .comparison-panel {
        overflow: hidden;
        border: 1px solid #dcdfe6;
        border-radius: 4px;

        .panel-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 16px;
          background: #f5f7fa;
          border-bottom: 1px solid #dcdfe6;

          h5 {
            margin: 0;
            color: #303133;
          }
        }

        .panel-content {
          min-height: 120px;
          padding: 16px;
          line-height: 1.6;
          word-break: break-word;

          &.original {
            color: #f56c6c;
            background: #fef0f0;
          }

          &.filtered {
            color: #409eff;
            background: #f0f9ff;
          }
        }
      }
    }

    .action-suggestions {
      h4 {
        margin-bottom: 16px;
        color: #303133;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
